package com.song.shiro.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;

/**
 * 自定义MyRealm用于认证和授权
 * AuthenticatingRealm是只负责认证（登录）的Realm父类
 */
public class MyAuthenticatingRealm extends AuthenticatingRealm {
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //将AuthenticationToken强转为UsernamePasswordToken，便于获取用户名和密码
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //获取浏览器输入的账号
        String username = token.getUsername();
        //从数据库中获取账号信息
        String dbUsername = username;
        if (!"admin".equals(dbUsername) && !"zhangsan".equals(dbUsername)){
            throw new UnknownAccountException("未知账号");
        }
        if ("zhangsan".equals(dbUsername)){
            throw new LockedAccountException("账号锁定");
        }
        //从数据库中获取账号信息
        String dbPassword = "123456";
        return new SimpleAuthenticationInfo(dbUsername, dbPassword, getName());
    }
}
